<?php
class File {
	const JPEG = "jpeg";
	const JPG = "jpg";
	const PNG = "png";
	const GIF = "gif";
	const MP3 = "mp3";
	const FLV = "flv";
	const SWF = "swf";
	
	static public function defineType($filename){
		$filename = strtolower($filename);
		$type = self::defineTypeExtension($filename);
		return $type;
	}	
	
	static public function defineTypeExtension($filename) {
		$posit = strripos($filename, ".") + 1;
		return substr($filename, $posit, strlen($filename)-$posit);
	}
	/**
	 * Get content from file 
	 * 
	 * @param $fileName Name of file
	 * 
	 * @return string the read string or false in case of error.
	 */
	static public function readFile($fileName){
		$result = "";
		if (is_file($fileName)){
			$handle = fopen($fileName, "rb");
			$size = filesize($fileName);
			if ($size>0)
				$result = fread($handle, $size);
			else 
				$result = '';
			fclose($handle);
			return $result;
		}
		return false;
	}
	/**
	 * Write text in any file
	 * 
	 * @param $fileName string Name of file
	 * @param $content string Text content of file
	 * 
	 * @return int
	 */
	static public function writeFile($fileName, $content){
		$dir = dirname($fileName);
		if(! file_exists($dir))
			mkdir($dir, 0755, true);
		if(! is_writable($dir))
			chmod($dir, 0755);
		$handle = fopen($fileName, "w");
		$result = fwrite($handle, $content);
		fclose($handle);
		chmod($fileName, 0755);
		return $result;
	}
	/**
	 * Get original file name. Delete from file name preffix cloased char $cloasedPreffixChar.
	 * 
	 * @param $file_name string Name of file
	 * @param $cloasedPreffixChar string Cloased preffix char
	 * 
	 * @return string Original file name. Name without preffix
	 */
	static public function getOriginalName($file_name, $cloasedPreffixChar = "_"){
		$filename = basename($file_name);
		return dirname($file_name)."/".substr_replace($filename, "", 0, strpos ($filename, $cloasedPreffixChar)+1);
	}
	/**
	 * Deleting list of files
	 * 
	 * @param $list array Array of file names
	 */
	static public function deleteFiles(array $list){
		$countDeleted= 0;
		foreach ($list as $file_name){
			if (file_exists($file_name)){
				$dir_name = dirname($file_name);
				//$chmod = self::getChmod($dir_name);
				chmod($dir_name, 0755);
				chmod($file_name, 0755);
				@unlink($file_name);
				//chmod($dir_name, $chmod);
				$countDeleted++;
			}
		}
		return $countDeleted;
	}
	/**
	 * Get chmod code
	 * 
	 * @param $file_name string Name of file or dir
	 * 
	 * @return int of int Chmod code
	 */
	static public function getChmod($file_name){
		return substr(sprintf('%o', fileperms($file_name)), -4);
	}
}

?>